<template>
  <div class="app-container">
    <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start" v-if="!isMobileView">
      <!-- 移动端顶部标题 -->
      <div class="mobile-header">
        <div class="page-title">{{ $route.params.id ? '编辑知识点' : '新增知识点' }}</div>
        <div class="back-button" @click="handleBack">
          <i class="el-icon-arrow-left"></i> 返回列表
        </div>
      </div>
    </el-row>
    
    <!-- 移动端头部 -->
    <div class="mobile-header" v-if="isMobileView">
      <div class="page-title">{{ $route.params.id ? '编辑知识点' : '新增知识点' }}</div>
      <div class="mobile-back" @click="handleBack">
        <i class="el-icon-arrow-left"></i>
      </div>
    </div>

    <!-- 骨架屏 -->
    <mobile-skeleton v-if="loading && isMobileView" type="form" :count="4" :showPagination="false" />
    
    <el-row :gutter="10" :class="{'mobile-layout': isMobileView}">
      <el-col :span="6" :xs="24" :sm="8" :class="{'hidden-mobile': isMobileView}">
        <div class="base_info" :class="{'mobile-base-info': isMobileView}">
          <span :style="{ color: theme }" v-if="!isMobileView">{{ $route.params.id ? '编辑知识点' : '新增知识点' }}</span>
          <el-form ref="form" :model="form" :label-width="isMobileView ? '100px' : '100px'" style="margin-top:10px" :rules="rules"
            :label-position="isMobileView ? 'top' : 'top'">
            <el-form-item label="知识点名称" prop="name">
              <el-input v-model="form.name" :size="isMobileView ? 'medium' : 'mini'" :class="{'mobile-input': isMobileView}"></el-input>
            </el-form-item>
            <el-form-item label="排序" v-if="$route.params.id">
              <el-input v-model="form.sort" :size="isMobileView ? 'medium' : 'mini'" :class="{'mobile-input': isMobileView}"></el-input>
            </el-form-item>

            <el-form-item label="所属分类" :required="true">
              <treeselect v-model="form.category" 
                :options="courseOptions" 
                :normalizer="normalizer"
                :disable-branch-nodes="true"
                placeholder="请选择分类" 
                :show-count="true"
                :size="isMobileView ? 'medium' : 'mini'"
                class="treeselect-main" 
                style="width:100%"
                :class="{'mobile-treeselect': isMobileView}"
                :clear-value-text="'清除'"
                :default-expand-level="1" />
            </el-form-item>

            <el-form-item label="描述" prop="desc">
              <el-input type="textarea" :rows="2" v-model="form.desc" :size="isMobileView ? 'medium' : 'mini'" 
                :class="{'mobile-textarea': isMobileView}"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      
      <el-col :span="18" :xs="24" :sm="16">
        <div class="course_content" :class="{'mobile-course-content': isMobileView}">
          <span :style="{ color: theme, fontWeight: 'bold' }" v-if="!isMobileView">内容编辑</span>
          <div v-else class="mobile-section-title">内容编辑</div>

          <QuillEditorForm :data='form.content' @dataChange="dataChange" ref="child" />

          <el-row>
            <el-col :span="24">
              <div :class="{'mobile-buttons': isMobileView}" style="text-align:center;margin-top:20px">
                <el-button type="primary" :size="isMobileView ? 'medium' : 'mini'"
                  :style="{ 
                    backgroundColor: theme, 
                    borderColor: theme, 
                    fontWeight: 'bold', 
                    width: isMobileView ? '45%' : 'auto',
                    height: isMobileView ? '40px' : 'auto'
                  }" 
                  @click="submitForm()">保存
                </el-button>
                <el-button plain :size="isMobileView ? 'medium' : 'small'" 
                  :style="{ 
                    width: isMobileView ? '45%' : 'auto',
                    height: isMobileView ? '40px' : 'auto'
                  }" 
                  @click="handleBack">取消</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import Editor from "@/views/vadmin/course/components/editor";
import QuillEditorForm from "@/views/vadmin/course/components/QuillEditorForm";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  categoryTree,
  knowledgeDetail,
  updateKnowledge,
  addKnowledge,
  listKnowledge,
} from "@/api/vadmin/course/course";
import { isMobileViewport, addViewportChangeListener, removeViewportChangeListener } from '@/utils/device';
// 引入骨架屏组件
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "newKnowledge",
  components: { Editor, Treeselect, QuillEditorForm, MobileSkeleton },
  data() {
    return {
      // 遮罩层
      loading: true,
      count: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      form: { name: "", desc: "无" },

      List: [],
      courseOptions: [],
      value: true,
      screenWidth: document.body.clientWidth,
      rules: {
        name: [
          { required: true, message: "知识点名称不能为空", trigger: "blur" },
        ],
        menuType: [
          { required: true, message: "分类不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "知识点内容不能为空", trigger: "blur" },
        ],
        desc: [{ required: true, message: "描述不能为空", trigger: "blur" }],
      },
      isMobileView: false,
      mediaQueryList: null,
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },

    editor() {
      return this.$refs.myQuillEditor.quill;
    },
    // 确保没有在computed中定义isMobile
  },
  watch: {
    "form.content": {
      handler(newVal) {
        this.form.content = newVal;
      },
      deep: true,
    },
    "form.category"(newVal, oldVal) {
      this.form.category = newVal;
    },
    screenWidth(val) {
      this.screenWidth = val;
    }
  },
  created() {
    // 初始化移动端检测
    this.mediaQueryList = window.matchMedia('(max-width: 768px)');
    // 初始化isMobile状态
    this.isMobileView = this.mediaQueryList.matches;
    // 添加媒体查询监听器
    this.mediaQueryHandler = (e) => {
      this.isMobileView = e.matches;
    };
    this.mediaQueryList.addListener(this.mediaQueryHandler);
    
    this.getTree();
    // this.getKnowledgeNum();
    if (this.$route.params.id || this.$route.params.id !== undefined) {
      this.getList();
    }
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.mediaQueryHandler);
    }
  },
  mounted() { },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth;
    },
    dataChange(val) {
      this.form.content = val;
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询列表 */
    getList() {
      knowledgeDetail(this.$route.params).then((response) => {
        this.form = response;
        this.form.category = response.category.id;
      });
    },
    getTree() {
      //课程分类
      categoryTree({ page_size: 1000, page: 1 }).then((response) => {
        // console.log("关联课程", response);
        this.courseOptions = response;
      });
    },
    handleBack() {
      this.$router.push({ name: "Knowledge", params: { queryParams: this.$route.params.queryParams } });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        // console.log("新增知识点", this.form);
        if (this.form.content == "" || this.form.content == null) {
          this.$message({
            message: "知识点内容不能为空",
            type: "error",
          });
        } else {
          if (valid) {
            this.loading = true;
            if (this.form.id != undefined) {
              updateKnowledge(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.loading = false;
              }).catch(() => {
                this.loading = false;
              });
            } else {
              delete this.form["sort"];
              addKnowledge(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.form = { name: "", content: "" };
                this.loading = false;
              }).catch(() => {
                this.loading = false;
              });
            }
          }
        }
      });
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name || node.label,
        children: node.children
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}

.drag-item {
  width: 200px;
  height: 50px;
  line-height: 50px;
  margin: auto;
  position: relative;
  background: rgb(118, 226, 240);
  margin-top: 20px;
}

.sortable-ghost {
  background: #fff !important;
}

ul {
  padding: 0 !important;
  width: 100%;
  display: block;
}

.base_info {
  background-color: #fff;
  padding: 20px;
  min-height: 200px;
  border-radius: 5px;
}

.course_content {
  background-color: #fff;
  padding: 20px;
  min-height: 200px;
  border-radius: 5px;
}

.mobile-layout {
  .el-row {
    margin-bottom: 0;
  }
}

.mobile-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  
  .page-title {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 10px;
  }
  
  .back-button {
    display: flex;
    align-items: center;
    padding: 8px 15px;
    background-color: #f5f7fa;
    border-radius: 8px;
    font-size: 14px;
    color: #606266;
    margin-top: 5px;
    cursor: pointer;
    
    i {
      margin-right: 5px;
    }
  }
}

.mobile-base-info {
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.mobile-course-content {
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  
  .mobile-section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: var(--theme);
  }
  
  /deep/ .ql-container {
    min-height: 200px;
    max-height: 300px;
    border-radius: 0 0 8px 8px;
  }
  
  /deep/ .ql-toolbar {
    padding: 5px;
    overflow-x: auto;
    white-space: nowrap;
    border-radius: 8px 8px 0 0;
    
    .ql-formats {
      margin-right: 5px;
    }
  }
}

.mobile-input {
  width: 100%;
  
  /deep/ .el-input__inner {
    height: 40px;
    border-radius: 8px;
    font-size: 15px;
  }
}

.mobile-textarea {
  width: 100%;
  
  /deep/ .el-textarea__inner {
    border-radius: 8px;
    padding: 10px;
    font-size: 15px;
  }
}

.mobile-treeselect {
  /deep/ .vue-treeselect__control {
    height: 40px;
    border-radius: 8px;
    
    .vue-treeselect__single-value {
      line-height: 40px;
      font-size: 15px;
    }
    
    .vue-treeselect__placeholder {
      line-height: 40px;
      font-size: 15px;
    }
  }
  
  /deep/ .vue-treeselect__menu {
    border-radius: 8px;
    
    .vue-treeselect__option {
      padding: 8px 15px;
      font-size: 15px;
    }
    
    .vue-treeselect__option-label {
      font-size: 15px;
    }
  }
}

.mobile-buttons {
  display: flex;
  justify-content: space-around;
  margin-top: 25px;
  
  .el-button {
    font-size: 16px;
  }
}

@media screen and (max-width: 768px) {
  .hidden-mobile {
    display: none;
  }
  
  /deep/ .vue-treeselect {
    font-size: 14px;
    
    .vue-treeselect__control {
      height: 40px;
    }
    
    .vue-treeselect__placeholder {
      font-size: 14px;
    }
  }
  
  /deep/ .ql-editor {
    font-size: 14px;
  }
}
</style>